// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.PurchaseChangeOrder;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.BdRateMapper;
import com.fowo.api.mapper.PurchaseChangeOrderMapper;
import com.fowo.api.mapper.PurchaseChangeOrderProductMapper;
import com.fowo.api.mapper.PurchaserMapper;
import com.fowo.api.mapper.SupplierMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.bd.rate.BdRateItemVo;
import com.fowo.api.model.bd.rate.BdRateSearchParamPo;
import com.fowo.api.model.purchase.change.order.PurchaseChangeOrderBulkAuditingAction;
import com.fowo.api.model.purchase.change.order.PurchaseChangeOrderExcelPo;
import com.fowo.api.model.purchase.change.order.PurchaseChangeOrderImportPo;
import com.fowo.api.model.purchase.change.order.PurchaseChangeOrderItemVo;
import com.fowo.api.model.purchase.change.order.PurchaseChangeOrderSearchParamPo;
import com.fowo.api.model.purchase.change.order.PurchaseChangeOrderVo;
import com.fowo.api.model.purchase.change.order.constant.PurchaseChangeOrderClosingPeriodEnums;
import com.fowo.api.model.purchase.change.order.constant.PurchaseChangeOrderFeePartTypeEnums;
import com.fowo.api.model.purchase.change.order.constant.PurchaseChangeOrderIncludingTaxEnums;
import com.fowo.api.model.purchase.change.order.constant.PurchaseChangeOrderInspectionTypeEnums;
import com.fowo.api.model.purchase.change.order.constant.PurchaseChangeOrderPurchaseTypeEnums;
import com.fowo.api.model.purchase.change.order.constant.PurchaseChangeOrderStatusEnums;
import com.fowo.api.model.purchase.change.order.product.PurchaseChangeOrderProductItemVo;
import com.fowo.api.model.purchase.change.order.product.PurchaseChangeOrderProductItemVoPages;
import com.fowo.api.model.purchase.change.order.product.PurchaseChangeOrderProductSearchParamPo;
import com.fowo.api.model.purchaser.PurchaserItemVo;
import com.fowo.api.model.purchaser.PurchaserSearchParamPo;
import com.fowo.api.model.supplier.SupplierItemVo;
import com.fowo.api.model.supplier.SupplierSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.service.PurchaseChangeOrderProductService;
import com.fowo.api.service.PurchaseChangeOrderService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.mapper.SysUserMapper;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.model.SysUserItemVo;
import com.fowo.api.sys.model.SysUserSearch;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 变更单 服务实现基类
 * @author 蜂窝蜜造平台 配置人：王阳阳，尹建栋
 */
@Slf4j
@DataObjectType(PurchaseChangeOrder.class)
@DS("ds24")
public class PurchaseChangeOrderBaseServiceImpl
  extends ServiceImpl<PurchaseChangeOrderMapper, PurchaseChangeOrder>
  implements PurchaseChangeOrderService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("createUserName", "su.`name`");
      put("supplierIdSupplierName", "s.`supplier_name`");
      put("widName", "w.`name`");
      put("optUidName", "su2.`name`");
      put("purchaserName", "p.`name`");
      put("currencyName", "br.`name`");
      put("creatorOpName", "su3.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected PurchaseChangeOrderService self;

  @Resource
  protected PurchaseChangeOrderProductService purchaseChangeOrderProductService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected SupplierMapper supplierMapper;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected SysUserMapper sysUserMapper;

  @Resource
  protected PurchaserMapper purchaserMapper;

  @Resource
  protected BdRateMapper bdRateMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected PurchaseChangeOrderBulkAuditingAction purchaseChangeOrderBulkAuditingAction;

  @Resource
  protected Validator validator;

  /**
   * 创建变更单
   * @param model 变更单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(PurchaseChangeOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    PurchaseChangeOrder entity = new PurchaseChangeOrder();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (currentUser != null) {
      entity.setCreatorOp(currentUser.getUserId());
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getCOrderSn())) {
      entity.setCOrderSn(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "PurchaseChangeOrder.cOrderSn")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return entity.getId();
    }
    throw new Exception("变更单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 变更单
   */
  protected void updateAllChilds(PurchaseChangeOrderVo model) throws Exception {
    if (model.getProductItem() != null) {
      purchaseChangeOrderProductService.saveAllByParentPurchaseChangeOrder(
        model.getId(),
        model.getProductItem()
      );
    }
  }

  /**
   * 更新变更单
   * @param model 变更单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(PurchaseChangeOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    PurchaseChangeOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("变更单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "createUser",
      "createTime",
      "id",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return true;
    }
    return false;
  }/**
   * 更新变更单（带空值）
   * @param model 变更单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(PurchaseChangeOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    PurchaseChangeOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("变更单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(PurchaseChangeOrder::getSupplierId, model.getSupplierId())
      .set(PurchaseChangeOrder::getWid, model.getWid())
      .set(PurchaseChangeOrder::getContactPerson, model.getContactPerson())
      .set(PurchaseChangeOrder::getContactNumber, model.getContactNumber())
      .set(
        PurchaseChangeOrder::getSettlementMethod,
        model.getSettlementMethod()
      )
      .set(PurchaseChangeOrder::getAdvanceRatio, model.getAdvanceRatio())
      .set(
        PurchaseChangeOrder::getSettlementDescribe,
        model.getSettlementDescribe()
      )
      .set(PurchaseChangeOrder::getPaymentMethod, model.getPaymentMethod())
      .set(
        PurchaseChangeOrder::getPurchaseCurrency,
        model.getPurchaseCurrency()
      )
      .set(PurchaseChangeOrder::getShippingPrice, model.getShippingPrice())
      .set(PurchaseChangeOrder::getOtherFee, model.getOtherFee())
      .set(PurchaseChangeOrder::getFeePartType, model.getFeePartType())
      .set(PurchaseChangeOrder::getIncludingTax, model.getIncludingTax())
      .set(PurchaseChangeOrder::getOptUid, model.getOptUid())
      .set(PurchaseChangeOrder::getPurchaser, model.getPurchaser())
      .set(PurchaseChangeOrder::getOrderTime, model.getOrderTime())
      .set(PurchaseChangeOrder::getPurchaseType, model.getPurchaseType())
      .set(PurchaseChangeOrder::getInspectionType, model.getInspectionType())
      .set(PurchaseChangeOrder::getOrderSn, model.getOrderSn())
      .set(PurchaseChangeOrder::getClosingPeriod, model.getClosingPeriod())
      .set(PurchaseChangeOrder::getRemarks, model.getRemarks())
      .set(PurchaseChangeOrder::getLastUpdateTime, model.getLastUpdateTime())
      .set(PurchaseChangeOrder::getLastUpdateUser, model.getLastUpdateUser())
      .eq(PurchaseChangeOrder::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(model.getId());
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(
    PurchaseChangeOrderSearchParamPo search
  ) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 产品(productItem) 对应的对象
    PurchaseChangeOrderProductSearchParamPo productItemSearchParam =
      new PurchaseChangeOrderProductSearchParamPo();
    productItemSearchParam.setDisableDataPremissions(true);
    productItemSearchParam.setParentPurchaseChangeOrderInList(ids);
    PurchaseChangeOrderProductMapper localPurchaseChangeOrderProductMapper =
      ContextHolder
        .getApplicationContext()
        .getBean(PurchaseChangeOrderProductMapper.class);
    productItemSearchParam.applySqlSegments();
    List<Long> productItemIdList =
      localPurchaseChangeOrderProductMapper.searchIds(productItemSearchParam);
    if (!productItemIdList.isEmpty()) {
      PurchaseChangeOrderProductService localPurchaseChangeOrderProductService =
        ContextHolder
          .getApplicationContext()
          .getBean(PurchaseChangeOrderProductService.class);
      localPurchaseChangeOrderProductService.batchDelete(productItemIdList);
    }
  }

  /**
   * 删除变更单
   * @param id 变更单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除变更单
   * @param ids 变更单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<PurchaseChangeOrderImportPo> excelToImportRow(
    PurchaseChangeOrderImportPo row,
    Integer rowNumber,
    PurchaseChangeOrderVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<PurchaseChangeOrderImportPo> ir =
      new ImportRow<PurchaseChangeOrderImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<PurchaseChangeOrderImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new PurchaseChangeOrderVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, PurchaseChangeOrderImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getSettlementMethod())) {
      List<SysDictAllItem> settlementMethodItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "settlementMethod",
          n -> sysDictService.getDictItems("SCM00004")
        );
      PurchaseChangeOrderVo finalVo = vo;
      settlementMethodItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getSettlementMethod()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setSettlementMethod(i.getItemValue()),
          () ->
            ir.addError(
              "settlementMethod",
              String.format(
                "必须为 %s 中之一",
                settlementMethodItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setAdvanceRatio(SheetUtils.tryToDecimal(row.getAdvanceRatio()));
    if (StringUtils.hasText(row.getPaymentMethod())) {
      List<SysDictAllItem> paymentMethodItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "paymentMethod",
          n -> sysDictService.getDictItems("SCM00005")
        );
      PurchaseChangeOrderVo finalVo = vo;
      paymentMethodItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPaymentMethod()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPaymentMethod(i.getItemValue()),
          () ->
            ir.addError(
              "paymentMethod",
              String.format(
                "必须为 %s 中之一",
                paymentMethodItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getPurchaseCurrency())) {
      List<SysDictAllItem> purchaseCurrencyItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "purchaseCurrency",
          n -> sysDictService.getDictItems("SCM00015")
        );
      PurchaseChangeOrderVo finalVo = vo;
      purchaseCurrencyItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPurchaseCurrency()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPurchaseCurrency(i.getItemValue()),
          () ->
            ir.addError(
              "purchaseCurrency",
              String.format(
                "必须为 %s 中之一",
                purchaseCurrencyItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setShippingPrice(SheetUtils.tryToDecimal(row.getShippingPrice()));
    vo.setOtherFee(SheetUtils.tryToDecimal(row.getOtherFee()));
    if (StringUtils.hasText(row.getFeePartType())) {
      vo.setFeePartType(
        PurchaseChangeOrderFeePartTypeEnums.toValue(row.getFeePartType())
      );
      if (vo.getFeePartType() == null) {
        ir.addError(
          "feePartType",
          "费用分配方式只能是：“不分配”, “按金额”, “按数量”"
        );
      }
    }
    if (StringUtils.hasText(row.getIncludingTax())) {
      vo.setIncludingTax(
        PurchaseChangeOrderIncludingTaxEnums.toValue(row.getIncludingTax())
      );
      if (vo.getIncludingTax() == null) {
        ir.addError("includingTax", "含税只能是：“否”, “是”");
      }
    }
    vo.setOrderTime(SheetUtils.tryToDateTime(row.getOrderTime()));
    if (StringUtils.hasText(row.getStatus())) {
      vo.setStatus(PurchaseChangeOrderStatusEnums.toValue(row.getStatus()));
      if (vo.getStatus() == null) {
        ir.addError("status", "状态只能是：“已驳回”, “ 待审核”, “已处理”");
      }
    }
    if (StringUtils.hasText(row.getPurchaseType())) {
      vo.setPurchaseType(
        PurchaseChangeOrderPurchaseTypeEnums.toValue(row.getPurchaseType())
      );
      if (vo.getPurchaseType() == null) {
        ir.addError("purchaseType", "采购类型只能是：“普通采购”");
      }
    }
    if (StringUtils.hasText(row.getInspectionType())) {
      vo.setInspectionType(
        PurchaseChangeOrderInspectionTypeEnums.toValue(row.getInspectionType())
      );
      if (vo.getInspectionType() == null) {
        ir.addError(
          "inspectionType",
          "质检类型只能是：“仓库质检”, “预检”, “免检”"
        );
      }
    }
    if (StringUtils.hasText(row.getClosingPeriod())) {
      vo.setClosingPeriod(
        PurchaseChangeOrderClosingPeriodEnums.toValue(row.getClosingPeriod())
      );
      if (vo.getClosingPeriod() == null) {
        ir.addError(
          "closingPeriod",
          "结算账期只能是：“入库后付款”, “入库号一个月付款”"
        );
      }
    }
    if (StringUtils.hasText(row.getShippingCurrency())) {
      List<SysDictAllItem> shippingCurrencyItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "shippingCurrency",
          n -> sysDictService.getDictItems("SCM00015")
        );
      PurchaseChangeOrderVo finalVo = vo;
      shippingCurrencyItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getShippingCurrency()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setShippingCurrency(i.getItemValue()),
          () ->
            ir.addError(
              "shippingCurrency",
              String.format(
                "必须为 %s 中之一",
                shippingCurrencyItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getOtherCurrency())) {
      List<SysDictAllItem> otherCurrencyItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "otherCurrency",
          n -> sysDictService.getDictItems("SCM00015")
        );
      PurchaseChangeOrderVo finalVo = vo;
      otherCurrencyItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getOtherCurrency()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setOtherCurrency(i.getItemValue()),
          () ->
            ir.addError(
              "otherCurrency",
              String.format(
                "必须为 %s 中之一",
                otherCurrencyItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setRate(SheetUtils.tryToDecimal(row.getRate()));
    vo.setOldAmount(SheetUtils.tryToDecimal(row.getOldAmount()));
    vo.setOldquantity(SheetUtils.tryToInteger(row.getOldquantity()));
    vo.setCreationTime(SheetUtils.tryToDate(row.getCreationTime()));
    SheetUtils.datePreviewFormat(row.getCreationTime(), row::setCreationTime);
    // 处理关联字段“供应商”
    if (
      !SheetUtils.isBlank(row.getSupplierIdSupplierName()) &&
      SheetUtils.isBlank(row.getSupplierId())
    ) {
      SupplierSearchParamPo supplierIdSearchParam = new SupplierSearchParamPo();
      supplierIdSearchParam.setLimit(2); // 最大只返回二行记录
      supplierIdSearchParam.setSupplierNameEq(
        SheetUtils.trim(row.getSupplierIdSupplierName())
      );
      supplierIdSearchParam.applySqlSegments();
      List<SupplierItemVo> supplierIdMatches = supplierMapper.search(
        supplierIdSearchParam
      );
      if (supplierIdMatches.size() == 0) {
        ir.addError("supplierIdSupplierName", "未能在供应商中找到匹配的数据");
      } else if (supplierIdMatches.size() > 1) {
        ir.addError(
          "supplierIdSupplierName",
          "关联不唯一，在供应商中找到多个匹配的数据"
        );
      } else {
        vo.setSupplierId(supplierIdMatches.get(0).getId());
      }
    }
    // 处理关联字段“采购仓库”
    if (
      !SheetUtils.isBlank(row.getWidName()) && SheetUtils.isBlank(row.getWid())
    ) {
      WarehouseSearchParamPo widSearchParam = new WarehouseSearchParamPo();
      widSearchParam.setLimit(2); // 最大只返回二行记录
      widSearchParam.setNameEq(SheetUtils.trim(row.getWidName()));
      widSearchParam.applySqlSegments();
      List<WarehouseItemVo> widMatches = warehouseMapper.search(widSearchParam);
      if (widMatches.size() == 0) {
        ir.addError("widName", "未能在仓库即时库存中找到匹配的数据");
      } else if (widMatches.size() > 1) {
        ir.addError(
          "widName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setWid(widMatches.get(0).getId());
      }
    }
    // 处理关联字段“采购员”
    if (
      !SheetUtils.isBlank(row.getOptUidName()) &&
      SheetUtils.isBlank(row.getOptUid())
    ) {
      SysUserSearch optUidSearchParam = new SysUserSearch();
      optUidSearchParam.setLimit(2); // 最大只返回二行记录
      optUidSearchParam.setNameEq(SheetUtils.trim(row.getOptUidName()));
      optUidSearchParam.applySqlSegments();
      List<SysUserItemVo> optUidMatches = sysUserMapper.search(
        optUidSearchParam
      );
      if (optUidMatches.size() == 0) {
        ir.addError("optUidName", "未能在用户中找到匹配的数据");
      } else if (optUidMatches.size() > 1) {
        ir.addError("optUidName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setOptUid(optUidMatches.get(0).getId());
      }
    }
    // 处理关联字段“采购方”
    if (
      !SheetUtils.isBlank(row.getPurchaserName()) &&
      SheetUtils.isBlank(row.getPurchaser())
    ) {
      PurchaserSearchParamPo purchaserSearchParam =
        new PurchaserSearchParamPo();
      purchaserSearchParam.setLimit(2); // 最大只返回二行记录
      purchaserSearchParam.setNameEq(SheetUtils.trim(row.getPurchaserName()));
      purchaserSearchParam.applySqlSegments();
      List<PurchaserItemVo> purchaserMatches = purchaserMapper.search(
        purchaserSearchParam
      );
      if (purchaserMatches.size() == 0) {
        ir.addError("purchaserName", "未能在采购方中找到匹配的数据");
      } else if (purchaserMatches.size() > 1) {
        ir.addError(
          "purchaserName",
          "关联不唯一，在采购方中找到多个匹配的数据"
        );
      } else {
        vo.setPurchaser(purchaserMatches.get(0).getId());
      }
    }
    // 处理关联字段“货币币种”
    if (
      !SheetUtils.isBlank(row.getCurrencyName()) &&
      SheetUtils.isBlank(row.getCurrency())
    ) {
      BdRateSearchParamPo currencySearchParam = new BdRateSearchParamPo();
      currencySearchParam.setLimit(2); // 最大只返回二行记录
      currencySearchParam.setNameEq(SheetUtils.trim(row.getCurrencyName()));
      currencySearchParam.applySqlSegments();
      List<BdRateItemVo> currencyMatches = bdRateMapper.search(
        currencySearchParam
      );
      if (currencyMatches.size() == 0) {
        ir.addError("currencyName", "未能在汇率中找到匹配的数据");
      } else if (currencyMatches.size() > 1) {
        ir.addError("currencyName", "关联不唯一，在汇率中找到多个匹配的数据");
      } else {
        vo.setCurrency(currencyMatches.get(0).getId());
      }
    }
    // 处理关联字段“变更创建人”
    if (
      !SheetUtils.isBlank(row.getCreatorOpName()) &&
      SheetUtils.isBlank(row.getCreatorOp())
    ) {
      SysUserSearch creatorOpSearchParam = new SysUserSearch();
      creatorOpSearchParam.setLimit(2); // 最大只返回二行记录
      creatorOpSearchParam.setNameEq(SheetUtils.trim(row.getCreatorOpName()));
      creatorOpSearchParam.applySqlSegments();
      List<SysUserItemVo> creatorOpMatches = sysUserMapper.search(
        creatorOpSearchParam
      );
      if (creatorOpMatches.size() == 0) {
        ir.addError("creatorOpName", "未能在用户中找到匹配的数据");
      } else if (creatorOpMatches.size() > 1) {
        ir.addError("creatorOpName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setCreatorOp(creatorOpMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<PurchaseChangeOrderImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<PurchaseChangeOrderImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            PurchaseChangeOrderImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              PurchaseChangeOrderImportPo row,
              AnalysisContext cxt
            ) {
              PurchaseChangeOrderVo vo = new PurchaseChangeOrderVo();
              ImportRow<PurchaseChangeOrderImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<PurchaseChangeOrderImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<PurchaseChangeOrderImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      PurchaseChangeOrderVo vo = new PurchaseChangeOrderVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"变更单号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "cOrderSn".equals(m.getField())
          )
      ) {
        vo.setCOrderSn(
          sysSerialService.getNewSerial(
            new NewSerialRequest(null, "PurchaseChangeOrder.cOrderSn")
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    PurchaseChangeOrderSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "settlementMethod",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00004")
      );
      exportOptions.addFieldMappingOption(
        "paymentMethod",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00005")
      );
      exportOptions.addFieldMappingOption(
        "purchaseCurrency",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00015")
      );
      exportOptions.addFieldMappingOption(
        "feePartType",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            PurchaseChangeOrderFeePartTypeEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "includingTax",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            PurchaseChangeOrderIncludingTaxEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "optUid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PurchaseChangeOrderItemVo) r).getOptUidName())
          )
      );
      exportOptions.addFieldMappingOption(
        "purchaser",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PurchaseChangeOrderItemVo) r).getPurchaserName())
          )
      );
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            PurchaseChangeOrderStatusEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "purchaseType",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            PurchaseChangeOrderPurchaseTypeEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "inspectionType",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            PurchaseChangeOrderInspectionTypeEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "closingPeriod",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            PurchaseChangeOrderClosingPeriodEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "shippingCurrency",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00015")
      );
      exportOptions.addFieldMappingOption(
        "otherCurrency",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00015")
      );
      exportOptions.addFieldMappingOption(
        "currency",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PurchaseChangeOrderItemVo) r).getCurrencyName())
          )
      );
      exportOptions.addFieldMappingOption(
        "creatorOp",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PurchaseChangeOrderItemVo) r).getCreatorOpName())
          )
      );
      exportOptions.addStringFields(
        "cOrderSn",
        "contactPerson",
        "contactNumber",
        "settlementMethod",
        "settlementDescribe",
        "paymentMethod",
        "purchaseCurrency",
        "feePartType",
        "includingTax",
        "optUidName",
        "purchaserName",
        "quantity",
        "amount",
        "status",
        "purchaseType",
        "inspectionType",
        "orderSn",
        "closingPeriod",
        "remarks",
        "shippingCurrency",
        "otherCurrency",
        "currencyName",
        "creatorOpName"
      );

      String fileName = String.format(
        "变更单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> settlementMethodItems = sysDictService.getDictItems(
      "SCM00004"
    );
    List<SysDictAllItem> paymentMethodItems = sysDictService.getDictItems(
      "SCM00005"
    );
    List<SysDictAllItem> purchaseCurrencyItems = sysDictService.getDictItems(
      "SCM00015"
    );
    List<SysDictAllItem> shippingCurrencyItems = sysDictService.getDictItems(
      "SCM00015"
    );
    List<SysDictAllItem> otherCurrencyItems = sysDictService.getDictItems(
      "SCM00015"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<PurchaseChangeOrderExcelPo> items =
      new ArrayList<PurchaseChangeOrderExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<PurchaseChangeOrderItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<PurchaseChangeOrderItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (PurchaseChangeOrderItemVo item : list) {
        PurchaseChangeOrderExcelPo excel = new PurchaseChangeOrderExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getSettlementMethod() != null) {
          settlementMethodItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getSettlementMethod()))
            .findFirst()
            .ifPresent(i -> excel.setSettlementMethod(i.getItemText()));
        }
        if (item.getPaymentMethod() != null) {
          paymentMethodItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getPaymentMethod()))
            .findFirst()
            .ifPresent(i -> excel.setPaymentMethod(i.getItemText()));
        }
        if (item.getPurchaseCurrency() != null) {
          purchaseCurrencyItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getPurchaseCurrency()))
            .findFirst()
            .ifPresent(i -> excel.setPurchaseCurrency(i.getItemText()));
        }
        excel.setFeePartType(
          PurchaseChangeOrderFeePartTypeEnums.toLabel(item.getFeePartType())
        );
        excel.setIncludingTax(
          PurchaseChangeOrderIncludingTaxEnums.toLabel(item.getIncludingTax())
        );
        excel.setStatus(
          PurchaseChangeOrderStatusEnums.toLabel(item.getStatus())
        );
        excel.setPurchaseType(
          PurchaseChangeOrderPurchaseTypeEnums.toLabel(item.getPurchaseType())
        );
        excel.setInspectionType(
          PurchaseChangeOrderInspectionTypeEnums.toLabel(
            item.getInspectionType()
          )
        );
        excel.setClosingPeriod(
          PurchaseChangeOrderClosingPeriodEnums.toLabel(item.getClosingPeriod())
        );
        if (item.getShippingCurrency() != null) {
          shippingCurrencyItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getShippingCurrency()))
            .findFirst()
            .ifPresent(i -> excel.setShippingCurrency(i.getItemText()));
        }
        if (item.getOtherCurrency() != null) {
          otherCurrencyItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getOtherCurrency()))
            .findFirst()
            .ifPresent(i -> excel.setOtherCurrency(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "变更单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(PurchaseChangeOrderExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过采购单号查询变更单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByOrderSn(String orderSn) {
    return this.baseMapper.getIdByOrderSn(orderSn);
  }

  /**
   * 通过采购单号查询变更单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByOrderSn(List<String> list) {
    return this.baseMapper.getIdsByOrderSn(list);
  }

  /**
   * 通过变更单主键查询采购单号
   */
  @Override
  public String getOrderSnById(Long id) {
    return this.baseMapper.getOrderSnById(id);
  }

  /**
   * 通过变更单主键查询采购单号列表
   */
  @Override
  public List<String> getOrderSnByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getOrderSnByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("orderSn"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 变更单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public PurchaseChangeOrderVo getVoById(Long id) throws Exception {
    PurchaseChangeOrderVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    PurchaseChangeOrderProductSearchParamPo productItemSearchParamPo =
      new PurchaseChangeOrderProductSearchParamPo();
    productItemSearchParamPo.setParentPurchaseChangeOrder(id);
    productItemSearchParamPo.getExtendData().put("queryMode", "sub");
    productItemSearchParamPo
      .getExtendData()
      .put("queryParent", "PurchaseChangeOrder");
    productItemSearchParamPo.applySqlSegments();
    vo.setProductItem(
      purchaseChangeOrderProductService.search(productItemSearchParamPo)
    );

    return vo;
  }

  /**
   * 分页查询变更单
   * @param search 查询条件
   * @return 变更单分页查询结果
   */
  @Override
  public Page<PurchaseChangeOrderItemVo> pageSearch(
    PurchaseChangeOrderSearchParamPo search
  ) {
    Page<PurchaseChangeOrderItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(PurchaseChangeOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(
    Page<PurchaseChangeOrderItemVo> pageResult
  ) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<PurchaseChangeOrderItemVo> pageResult,
    String sort
  ) {
    if (
      pageResult == null ||
      pageResult.getRecords() == null ||
      pageResult.getRecords().isEmpty()
    ) {
      return pageResult;
    }
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    PurchaseChangeOrderProductSearchParamPo productItemSearchParamPo =
      new PurchaseChangeOrderProductSearchParamPo();
    productItemSearchParamPo.setSort(sort);
    productItemSearchParamPo.setPageSize(200);
    productItemSearchParamPo.setParentPurchaseChangeOrderInList(
      pageResult
        .getRecords()
        .stream()
        .map(PurchaseChangeOrderItemVo::getId)
        .collect(Collectors.toList())
    );

    Map<String, Page<PurchaseChangeOrderProductItemVoPages>> productItemMaps =
      purchaseChangeOrderProductService.pagesByParentPurchaseChangeOrder(
        productItemSearchParamPo
      );

    for (PurchaseChangeOrderItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put(
        "productItem",
        productItemMaps.get(itemVo.getId().toString())
      );
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 变更单分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(PurchaseChangeOrderSearchParamPo search) {
    return appendWithChild(
      pageSearch(search),
      search.toChildSort("productItem")
    );
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    PurchaseChangeOrderSearchParamPo search
  ) {
    PurchaseChangeOrderSearchParamPo parentSearchParam =
      new PurchaseChangeOrderSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<PurchaseChangeOrderItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      PurchaseChangeOrderItemVo itemVo = parentList.get(0);

      PurchaseChangeOrderProductSearchParamPo productItemSearchParamPo =
        new PurchaseChangeOrderProductSearchParamPo();
      productItemSearchParamPo.setPageSize(search.getPageSize());
      productItemSearchParamPo.setCurrent(search.getCurrent());
      productItemSearchParamPo.setParentPurchaseChangeOrder(itemVo.getId());
      return purchaseChangeOrderProductService.pageSearch(
        productItemSearchParamPo
      );
    } else {
      return null;
    }
  }

  /**
   * 变更单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'PurchaseChangeOrderOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<PurchaseChangeOrderItemVo>> searchOptions(
    PurchaseChangeOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询变更单
   * @param search 查询条件
   * @return 变更单列表查询结果
   */
  @Override
  public List<PurchaseChangeOrderItemVo> search(
    PurchaseChangeOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询变更单最后更新时间
   * @param search 查询条件
   * @return 变更单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(PurchaseChangeOrderSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 返回满足搜索条件的统计信息
   * @param search 搜索参数
   */
  @Override
  public Map<String, Object> searchForStatistical(
    PurchaseChangeOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchForStatistical(search);
  }

  /**
   * 批量审核
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了批量审核操作"
  )
  @Override
  public void bulkAuditing(List<Long> ids) throws Exception {
    if (purchaseChangeOrderBulkAuditingAction == null) {
      throw new Exception("此操作当前不可用");
    }
    purchaseChangeOrderBulkAuditingAction.run(ids);
  }

  /**
   * 全部
   */
  @Override
  public List<PurchaseChangeOrderItemVo> allAlter(
    PurchaseChangeOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.allAlter(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<PurchaseChangeOrderItemVo> allAlterPage(
    PurchaseChangeOrderSearchParamPo search
  ) {
    Page<PurchaseChangeOrderItemVo> allAlterPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return allAlterPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return allAlterPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    allAlterPage =
      this.baseMapper.allAlterPage(
          search.toPage(this.baseMapper.allAlterCount(search)),
          search
        );
    List<Long> recordIds = allAlterPage
      .getRecords()
      .stream()
      .map(PurchaseChangeOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return allAlterPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return allAlterPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    allAlterPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return allAlterPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 变更单分页查询结果
   */
  @Override
  public Page<?> allAlterPageWithChildSearch(
    PurchaseChangeOrderSearchParamPo search
  ) {
    return appendWithChild(
      allAlterPage(search),
      search.toChildSort("productItem")
    );
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date allAlterLastUpdateTime(PurchaseChangeOrderSearchParamPo search) {
    return this.baseMapper.allAlterLastUpdateTime(search);
  }

  /**
   * 待审批
   */
  @Override
  public List<PurchaseChangeOrderItemVo> pendingApproval(
    PurchaseChangeOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.pendingApproval(search);
  }

  /**
   * 待审批分页
   */
  @Override
  public Page<PurchaseChangeOrderItemVo> pendingApprovalPage(
    PurchaseChangeOrderSearchParamPo search
  ) {
    Page<PurchaseChangeOrderItemVo> pendingApprovalPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return pendingApprovalPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return pendingApprovalPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    pendingApprovalPage =
      this.baseMapper.pendingApprovalPage(
          search.toPage(this.baseMapper.pendingApprovalCount(search)),
          search
        );
    List<Long> recordIds = pendingApprovalPage
      .getRecords()
      .stream()
      .map(PurchaseChangeOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return pendingApprovalPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return pendingApprovalPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    pendingApprovalPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return pendingApprovalPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 变更单分页查询结果
   */
  @Override
  public Page<?> pendingApprovalPageWithChildSearch(
    PurchaseChangeOrderSearchParamPo search
  ) {
    return appendWithChild(
      pendingApprovalPage(search),
      search.toChildSort("productItem")
    );
  }

  /**
   * 查询待审批最后更新时间
   * @param search 查询条件
   * @return 待审批最后更新时间
   */
  @Override
  public Date pendingApprovalLastUpdateTime(
    PurchaseChangeOrderSearchParamPo search
  ) {
    return this.baseMapper.pendingApprovalLastUpdateTime(search);
  }

  /**
   * 已处理
   */
  @Override
  public List<PurchaseChangeOrderItemVo> processed(
    PurchaseChangeOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.processed(search);
  }

  /**
   * 已处理分页
   */
  @Override
  public Page<PurchaseChangeOrderItemVo> processedPage(
    PurchaseChangeOrderSearchParamPo search
  ) {
    Page<PurchaseChangeOrderItemVo> processedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return processedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return processedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    processedPage =
      this.baseMapper.processedPage(
          search.toPage(this.baseMapper.processedCount(search)),
          search
        );
    List<Long> recordIds = processedPage
      .getRecords()
      .stream()
      .map(PurchaseChangeOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return processedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return processedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    processedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return processedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 变更单分页查询结果
   */
  @Override
  public Page<?> processedPageWithChildSearch(
    PurchaseChangeOrderSearchParamPo search
  ) {
    return appendWithChild(
      processedPage(search),
      search.toChildSort("productItem")
    );
  }

  /**
   * 查询已处理最后更新时间
   * @param search 查询条件
   * @return 已处理最后更新时间
   */
  @Override
  public Date processedLastUpdateTime(PurchaseChangeOrderSearchParamPo search) {
    return this.baseMapper.processedLastUpdateTime(search);
  }

  /**
   * 已驳回
   */
  @Override
  public List<PurchaseChangeOrderItemVo> rejected(
    PurchaseChangeOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.rejected(search);
  }

  /**
   * 已驳回分页
   */
  @Override
  public Page<PurchaseChangeOrderItemVo> rejectedPage(
    PurchaseChangeOrderSearchParamPo search
  ) {
    Page<PurchaseChangeOrderItemVo> rejectedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return rejectedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return rejectedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    rejectedPage =
      this.baseMapper.rejectedPage(
          search.toPage(this.baseMapper.rejectedCount(search)),
          search
        );
    List<Long> recordIds = rejectedPage
      .getRecords()
      .stream()
      .map(PurchaseChangeOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return rejectedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return rejectedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    rejectedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return rejectedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 变更单分页查询结果
   */
  @Override
  public Page<?> rejectedPageWithChildSearch(
    PurchaseChangeOrderSearchParamPo search
  ) {
    return appendWithChild(
      rejectedPage(search),
      search.toChildSort("productItem")
    );
  }

  /**
   * 查询已驳回最后更新时间
   * @param search 查询条件
   * @return 已驳回最后更新时间
   */
  @Override
  public Date rejectedLastUpdateTime(PurchaseChangeOrderSearchParamPo search) {
    return this.baseMapper.rejectedLastUpdateTime(search);
  }
}
